import {
  CommandDialog,
  type CommandDialogPlacement,
  BaseCommand,
  http,
  CSLineSegments,
  getQueryParam,
  QueryParamKeys,
} from '@amcax/base';
import './index.scss';
import { wsApi } from '../../../../server';
import { Input, Menu, Image, Button, Modal } from 'antd';
import { useEffect, useState } from 'react';
import { AirFormDataLike, cmdAirfoilAPI } from './cmdAirfoilAPI';
import SubMenu from 'antd/lib/menu/SubMenu';
import { Vector3 } from 'three';
import { clearLocalListDatas } from '../../widgets/RightNavigation/panels/InputPanel';
import { ctx2, previewer, userEvents } from '../../../../module';

// 翼型
interface AirfoilCommandProps {
  title: string;
  onClose: () => void;
  placement: CommandDialogPlacement;
}

/**
 * 清除场景中所有模型
 */
export const clearScene = async () => {
  const length = ctx2.cadScene.edgeGroup.children.length;
  if (length > 0) {
    const model_dxids = [];
    for (let i = 0; i < length; i++) {
      const edge = ctx2.cadScene.edgeGroup.children[i] as CSLineSegments;
      const dxid = edge.modelDxid;
      if (dxid) {
        model_dxids.push(dxid);
      }
    }
    wsApi.delete(model_dxids);
  }
};

const documentId = getQueryParam<string>(QueryParamKeys.DOCUMENT_ID);
function AirfoilCommand({ title, onClose, placement }: AirfoilCommandProps) {
  /**几何信息*/
  const [airFormData, setAirFormData] = useState<AirFormDataLike>({
    camber_max: 0.02,
    camber_max_pos: 0.3,
    thickness_max: 0.12,
    thickness_max_pos: 0.3,
    leading_radius_index: 8,
    lift_angle: 0,
    mach_number: 0.785,
    reynolds_number: 5e6,
  });
  /**编辑状态*/
  const [open, setOpen] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [isFirstCreate, setIsFirstCreate] = useState(true);
  const [dxid, setDxid] = useState(null);

  const edgeGroup = ctx2.cadScene.edgeGroup;

  useEffect(() => {
    // 判断是否已存在翼型
    if (edgeGroup.children.length > 0) {
      setIsFirstCreate(false);
      const edge = edgeGroup.children[0] as CSLineSegments;
      setDxid(edge.modelDxid);
      updateInfo();
    }
  }, []);

  /**同步表单参数 */
  const updateInfo = async () => {
    getAirData().then((data) => {
      const params = JSON.parse(data);
      if (!params.camber_max) return;
      const airformParams = {
        camber_max: params.camber_max,
        camber_max_pos: params.camber_max_pos,
        thickness_max: params.thickness_max,
        thickness_max_pos: params.thickness_max_pos,
        leading_radius_index: params.leading_radius_index,
        lift_angle: params.lift_angle,
        mach_number: params.mach_number,
        reynolds_number: params.reynolds_number,
      };
      setAirFormData(airformParams);
    });
  };

  /**nextCore储存数据 */
  const saveAirData = async () => {
    const params = {
      camber_max: airFormData.camber_max,
      camber_max_pos: airFormData.camber_max_pos,
      thickness_max: airFormData.thickness_max,
      thickness_max_pos: airFormData.thickness_max_pos,
      leading_radius_index: airFormData.leading_radius_index,
      lift_angle: airFormData.lift_angle,
      mach_number: airFormData.mach_number,
      reynolds_number: airFormData.reynolds_number,
    };
    const data = JSON.stringify(params);
    await wsApi.saveAppData(documentId + 'params', data);
  };

  /**nextCore获取数据 */
  const getAirData = async () => {
    return await wsApi.getAppData(documentId + 'params');
  };

  /**修改表单参数 */
  const handleAirFormDataChange = () => (event) => {
    let { name, value } = event.target;
    console.log({ value });
    if (isNaN(value)) {
      return;
    }
    setAirFormData((prevState) => ({
      ...prevState,
      [name]: value,
    }));
  };

  /**校验表单参数 */
  const checkAirformData = (minValue, maxValue) => (event) => {
    let { name, value, type } = event.target;
    if (type === 'number') value = Number(value);
    if (isNaN(value)) {
      return;
    }
    if (value < minValue) {
      value = minValue;
    } else if (value > maxValue) {
      value = maxValue;
    }
    setAirFormData((prevState) => ({
      ...prevState,
      [name]: value,
    }));
  };

  /**
   * 创建翼型
   */
  const createAirfoil = async () => {
    if (edgeGroup.children.length > 1) {
      setOpen(true);
    } else {
      await executeCmdAirfoil();
      await saveAirData();
      clearLocalListDatas();
      userEvents.emit('sceneEmpty', false);
      onClose();
    }
  };

  /**
   * 生成翼型
   * 请求接口 获取翼型数据 进入生成命令
   */
  const executeCmdAirfoil = async (editChange = false) => {
    const paramData = await new Promise<Array<Vector3>>(async (resolve) => {
      const params = {
        camber_max: airFormData.camber_max,
        camber_max_pos: airFormData.camber_max_pos,
        thickness_max: airFormData.thickness_max,
        thickness_max_pos: airFormData.thickness_max_pos,
        leading_radius_index: airFormData.leading_radius_index,
      };
      // 翼型生成
      const generateAddr = `/airfoil/v1/${documentId}/generate`;
      await http.post(generateAddr, params).then((res) => {
        const jsonPoints = JSON.stringify(res.data.data);
        const pointsPos = JSON.parse(jsonPoints);
        const points3d = pointsPos.map((item) => {
          return new Vector3(item.x, item.y, 0);
        });
        resolve(points3d);
      });
    });
    const data = {
      params: paramData,
      dxid: dxid,
    };
    if (isFirstCreate) {
      await cmdAirfoilAPI.invoke(data).then((res) => {
        setDxid(res);
      });
    } else if (editChange) {
      data.dxid = null;
      await cmdAirfoilAPI.invoke(data).then((res) => {
        setDxid(res);
      });
    } else {
      await cmdAirfoilAPI.invoke(data);
    }
  };

  /**
   * 取消
   */
  const cancel = async () => {
    await previewer.clear();
    onClose();
  };

  /**
   * 编辑后 更新翼型提示框
   */
  const handleOk = async () => {
    setConfirmLoading(true);
    await clearScene();
    await executeCmdAirfoil(true);
    setConfirmLoading(false);
    clearLocalListDatas();
    onClose();
  };

  const handleCancel = () => {
    setOpen(false);
    updateInfo();
  };

  return (
    <CommandDialog
      title={title}
      onClose={onClose}
      placement={placement}>
      <div className='box'>
        <Menu
          defaultSelectedKeys={['999']}
          defaultOpenKeys={['sub1', 'sub2', 'sub3']}
          mode='inline'
          className='meun-panel'>
          <SubMenu
            key='sub1'
            title={<span className='menu-title'>几何信息</span>}
            className='meun-panel1'>
            <Image
              src={process.env.PUBLIC_URL + '/images/airfoil.png'}
              style={{ width: '290px' }}
            />
            <Menu.Item
              className='menu-child'
              style={{ paddingLeft: '24px' }}>
              <div className='menu-child1'>前缘半径指数(R)</div>
              <div className='input1'>
                <Input
                  name='leading_radius_index'
                  type='number'
                  min='0.8'
                  max='8.0'
                  step='0.1'
                  value={airFormData.leading_radius_index}
                  style={{ borderRadius: '10px', pointerEvents: 'auto' }}
                  onChange={handleAirFormDataChange()}
                  onBlur={checkAirformData(0.8, 8.0)}
                  onClick={(e) => {
                    e.stopPropagation();
                  }}
                />
              </div>
            </Menu.Item>
            <Menu.Item
              className='menu-child'
              style={{ paddingLeft: '24px' }}>
              <div className='menu-child1'>最大厚度(T)</div>
              <div className='input1'>
                <Input
                  name='thickness_max'
                  type='number'
                  min='0.04'
                  max='0.4'
                  step='0.01'
                  value={airFormData.thickness_max}
                  style={{ borderRadius: '10px', pointerEvents: 'auto' }}
                  onChange={handleAirFormDataChange()}
                  onBlur={checkAirformData(0.04, 0.4)}
                  onClick={(e) => {
                    e.stopPropagation();
                  }}
                />
              </div>
            </Menu.Item>
            <Menu.Item
              className='menu-child'
              style={{ paddingLeft: '24px' }}>
              <div className='menu-child1'>最大厚度位置(Xt)</div>
              <div className='input1'>
                <Input
                  name='thickness_max_pos'
                  type='number'
                  min='0.2'
                  max='0.6'
                  step='0.1'
                  value={airFormData.thickness_max_pos}
                  style={{ borderRadius: '10px', pointerEvents: 'auto' }}
                  onChange={handleAirFormDataChange()}
                  onBlur={checkAirformData(0.2, 0.6)}
                  onClick={(e) => {
                    e.stopPropagation();
                  }}
                />
              </div>
            </Menu.Item>
            <Menu.Item
              className='menu-child'
              style={{ paddingLeft: '24px' }}>
              <div className='menu-child1'>最大弯度(F)</div>
              <div className='input1'>
                <Input
                  name='camber_max'
                  type='number'
                  min='0'
                  max='0.1'
                  step='0.01'
                  value={airFormData.camber_max}
                  style={{ borderRadius: '10px', pointerEvents: 'auto' }}
                  onChange={handleAirFormDataChange()}
                  onBlur={checkAirformData(0.0, 0.1)}
                  onClick={(e) => {
                    e.stopPropagation();
                  }}
                />
              </div>
            </Menu.Item>
            <Menu.Item
              className='menu-child'
              style={{ paddingLeft: '24px' }}>
              <div className='menu-child1'>最大弯度位置(Xf)</div>
              <div className='input1'>
                <Input
                  name='camber_max_pos'
                  type='number'
                  min='0.1'
                  max='0.9'
                  step='0.1'
                  value={airFormData.camber_max_pos}
                  style={{ borderRadius: '10px', pointerEvents: 'auto' }}
                  onChange={handleAirFormDataChange()}
                  onBlur={checkAirformData(0.1, 0.9)}
                  onClick={(e) => {
                    e.stopPropagation();
                  }}
                />
              </div>
            </Menu.Item>
          </SubMenu>
          <div
            style={{
              display: 'flex',
              paddingTop: '10px',
              paddingBottom: '10px',
              paddingRight: '4px',
              justifyContent: 'right',
            }}>
            <div style={{ paddingLeft: '0px', marginRight: '8px' }}>
              <Button
                style={{ borderRadius: '5px' }}
                onClick={cancel}>
                {'取消'}
              </Button>
            </div>
            <div style={{ paddingRight: '0px' }}>
              <Button
                type='primary'
                style={{ borderRadius: '5px' }}
                onClick={createAirfoil}>
                {'生成'}
              </Button>
            </div>
          </div>
        </Menu>
        <Modal
          title='修改提示'
          open={open}
          onCancel={handleCancel}
          onOk={handleOk}
          confirmLoading={confirmLoading}
          okText='继续'
          cancelText='取消'
          style={{ borderRadius: '10px' }}>
          <p>您已进行数据编辑，重新生成翼型将清除之前数据，是否继续？</p>
        </Modal>
      </div>
    </CommandDialog>
  );
}

export const cmdAirfoil: BaseCommand = {
  id: 'CmdAirfoil',
  label: '创建翼型',
  icon: 'commands/airfoil/create-airfoil',
  create: (label: string, onClose: () => void) => (
    <AirfoilCommand
      title={'创建翼型'}
      onClose={onClose}
      placement='topLeft'
    />
  ),
};
